/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package base;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jdom.Element;
import org.jdom.JDOMException;

/**
 *
 * @author tacio
 */
public class RssPooler {

    private Task task;

    public RssPooler(Task task) {
        this.task = task;
    }

    public URL pool() throws MalformedURLException {
        URL torrentURL = null;
        Pattern pattern = Pattern.compile(task.getSearchString(), Pattern.CASE_INSENSITIVE);

        try {
            List<Element> itemList = Feed.getRssItems(task.getUrl());
            for (Element element : itemList) {
                Element description = element.getChild("description");
                String[] attributes = description.getText().split(";");
                Matcher matcher = pattern.matcher(attributes[0]);
                if (matcher.find()) {
                    Element enclosure = element.getChild("enclosure");
                    String url = enclosure.getAttributeValue("url").replaceAll("\"", "");
                    torrentURL = new URL(url);
                    break;
                }
            }

        } catch (MalformedURLException ex) {
            Logger.getLogger(RssPooler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(RssPooler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JDOMException ex) {
            Logger.getLogger(RssPooler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return torrentURL;
    }
}
